from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Dict, List, Optional
import json
import time
import asyncio
from enum import Enum


class MessageType(Enum):
    TEXT = "text"
    IMAGE = "image"
    FILE = "file"


class CustomerMessage(BaseModel):
    user_id: str
    message: str
    message_type: MessageType = MessageType.TEXT
    session_id: Optional[str] = None


class AIResponse(BaseModel):
    reply: str
    session_id: str
    confidence: float
    suggested_questions: List[str] = []
    needs_human: bool = False


app = FastAPI(title="AI客服系统")


class AICustomerService:
    def __init__(self):
        self.sessions: Dict[str, Dict] = {}
        self.knowledge_base = self._load_knowledge_base()
        self.faq_responses = self._load_faq_responses()

    def _load_knowledge_base(self) -> Dict:
        """加载知识库"""
        return {
            "product_info": {
                "价格": ["我们的产品价格根据配置不同而有所差异..."],
                "功能": ["产品主要功能包括：智能客服、自动回复..."],
                "售后": ["我们提供7x24小时技术支持..."]
            },
            "common_issues": {
                "登录问题": ["请检查网络连接，或尝试重置密码..."],
                "支付问题": ["支付失败可能是由于银行卡限额..."]
            }
        }

    def _load_faq_responses(self) -> Dict[str, str]:
        """加载常见问题回复"""
        return {
            "你好": "您好！欢迎使用我们的AI客服，请问有什么可以帮您？",
            "谢谢": "不客气！很高兴能为您服务，如有其他问题请随时联系。",
            "再见": "感谢您的咨询，再见！祝您生活愉快！",
            "人工客服": "正在为您转接人工客服，请稍等...",
            "工作时间": "我们的客服工作时间是每天9:00-18:00"
        }

    async def process_message(self, message: CustomerMessage) -> AIResponse:
        """处理用户消息"""
        session_id = message.session_id or self._create_session(message.user_id)

        # 更新会话历史
        self._update_session(session_id, message.message)

        # 分析用户意图
        intent = await self._analyze_intent(message.message)

        # 生成回复
        if intent.get("needs_human", False):
            reply = "您的问题比较复杂，正在为您转接人工客服..."
            needs_human = True
        else:
            reply = await self._generate_reply(message.message, intent, session_id)
            needs_human = False

        return AIResponse(
            reply=reply,
            session_id=session_id,
            confidence=intent.get("confidence", 0.8),
            suggested_questions=self._get_suggested_questions(intent),
            needs_human=needs_human
        )

    async def _analyze_intent(self, message: str) -> Dict:
        """分析用户意图"""
        message_lower = message.lower()

        # 关键词匹配
        if any(word in message_lower for word in ["价格", "多少钱", "费用"]):
            return {"intent": "price_inquiry", "confidence": 0.9}
        elif any(word in message_lower for word in ["功能", "能做什么", "特性"]):
            return {"intent": "feature_inquiry", "confidence": 0.85}
        elif any(word in message_lower for word in ["问题", "故障", "错误"]):
            return {"intent": "troubleshooting", "confidence": 0.8}
        elif any(word in message_lower for word in ["人工", "真人", "转接"]):
            return {"intent": "human_agent", "needs_human": True, "confidence": 0.95}
        else:
            return {"intent": "general_inquiry", "confidence": 0.7}

    async def _generate_reply(self, message: str, intent: Dict, session_id: str) -> str:
        """生成回复"""
        # 检查固定话术
        fixed_reply = self.faq_responses.get(message)
        if fixed_reply:
            return fixed_reply

        # 基于意图生成回复
        intent_type = intent.get("intent", "general_inquiry")

        if intent_type == "price_inquiry":
            return "我们的产品提供多种套餐：基础版¥99/月，专业版¥199/月，企业版请联系销售。您需要了解哪个套餐的详细信息？"
        elif intent_type == "feature_inquiry":
            return "我们的AI客服系统主要功能：\n• 智能自动回复\n• 多轮对话管理\n• 知识库检索\n• 人工转接\n• 数据分析报表\n您对哪个功能感兴趣？"
        elif intent_type == "troubleshooting":
            return "遇到问题了吗？请描述具体现象，或尝试以下操作：\n1. 重新登录账号\n2. 清除缓存\n3. 检查网络连接\n需要更详细的帮助吗？"
        else:
            # 使用AI模型生成回复（这里可以接入GPT等模型）
            return await self._generate_ai_reply(message, session_id)

    async def _generate_ai_reply(self, message: str, session_id: str) -> str:
        """使用AI模型生成回复"""
        # 这里可以接入 OpenAI GPT、文心一言、通义千问等
        # 示例使用简单的规则引擎

        session_history = self.sessions.get(session_id, {}).get("history", [])
        context = " ".join([f"用户:{msg}" for msg in session_history[-3:]])  # 最近3条历史

        # 模拟AI回复生成
        ai_prompt = f"""
        基于以下对话历史和当前问题，生成专业、友好的客服回复：

        对话历史：{context}
        当前问题：{message}

        回复要求：
        - 专业、友好、有帮助
        - 长度在50-100字
        - 如果无法确定答案，建议转人工
        """

        # 这里应该是调用AI模型的代码
        # 暂时返回示例回复
        return "感谢您的咨询！我理解您的问题是关于产品使用的。建议您查看我们的帮助文档，或提供更多详细信息以便我更好地协助您。"

    def _get_suggested_questions(self, intent: Dict) -> List[str]:
        """获取推荐问题"""
        intent_type = intent.get("intent")

        suggestions = {
            "price_inquiry": ["有哪些套餐？", "企业版价格多少？", "有免费试用吗？"],
            "feature_inquiry": ["支持哪些平台？", "有API接口吗？", "如何集成到网站？"],
            "troubleshooting": ["登录不了怎么办？", "数据丢失如何恢复？", "如何联系技术支持？"],
            "general_inquiry": ["产品优势是什么？", "如何开始使用？", "有使用教程吗？"]
        }

        return suggestions.get(intent_type, ["如何购买？", "技术支持", "产品文档"])

    def _create_session(self, user_id: str) -> str:
        """创建新会话"""
        session_id = f"{user_id}_{int(time.time())}"
        self.sessions[session_id] = {
            "user_id": user_id,
            "created_at": time.time(),
            "history": [],
            "message_count": 0
        }
        return session_id

    def _update_session(self, session_id: str, message: str):
        """更新会话历史"""
        if session_id in self.sessions:
            self.sessions[session_id]["history"].append(message)
            self.sessions[session_id]["message_count"] += 1


# 初始化客服引擎
ai_customer_service = AICustomerService()


@app.post("/chat", response_model=AIResponse)
async def chat_endpoint(message: CustomerMessage):
    """聊天接口"""
    try:
        response = await ai_customer_service.process_message(message)
        return response
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"处理消息时出错: {str(e)}")


@app.get("/session/{session_id}")
async def get_session_info(session_id: str):
    """获取会话信息"""
    if session_id in ai_customer_service.sessions:
        return ai_customer_service.sessions[session_id]
    else:
        raise HTTPException(status_code=404, detail="会话不存在")